<template>
  <div class="user">
    <el-col :span="24">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
    </el-col>
    <el-col :span="24" class="user-content">
      <!-- 输入框 -->
      <search :placeholder="placeholder" @search="handleSearch"></search>
      <el-col :span="4">
        <el-button type="primary" @click="isShow = true">添加用户</el-button>
      </el-col>
      <el-col :span="24">
        <el-table :data="userList.users" border style="width: 100%">
          <el-table-column prop="id" label="id" width="140">
          </el-table-column>
          <el-table-column prop="username" label="姓名" width="140">
          </el-table-column>
          <el-table-column prop="email" label="邮箱" width="200">
          </el-table-column>
          <el-table-column prop="create_time" label="电话" width="140">
          </el-table-column>
          <el-table-column prop="role_name" label="角色" width="140">
          </el-table-column>
          <el-table-column prop="mg_state" label="状态" width="140">
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template slot-scope="scope">
              <el-button type="primary" @click="editUser(scope.row)">编辑</el-button>
              <el-button type="danger" @click="delUser(scope.row)">删除</el-button>
              <el-button type="info" @click="setRole(scope.row)">设置</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="9" style="margin-top: 20px;">
        <page :total="total" :current-page="pagenum" :page-size.sync="pagesize" @update:currentPage="updateCurrentPage"
          @update:pageSize="updatePageSize">
        </page>
      </el-col>
    </el-col>
    <el-form label-width="100px" class="user-form" v-show="isShow" key="user-form">
      <!-- 标题 -->
      <p>添加用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="form.username"></el-input>
        <span>{{ form.usernameMsg }}</span>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" autocomplete="off" v-model="form.password"></el-input>
        <span>{{ form.passwordMsg }}</span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="form.email"></el-input>
        <span>{{ form.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="form.phone"></el-input>
        <span>{{ form.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addUser">确认</el-button>
        <el-button @click="isShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <el-form label-width="100px" class="edit-form" key="edit-form" v-show="editIsShow">
      <!-- 标题 -->
      <p>编辑用户</p>
      <el-form-item label="用户名" prop="username">
        <el-input type="text" autocomplete="off" v-model="editForm.username" :disabled="true"></el-input>
        <span></span>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input type="email" autocomplete="off" v-model="editForm.email"></el-input>
        <span>{{ editForm.emailMsg }}</span>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input type="number" v-model="editForm.phone"></el-input>
        <span>{{ editForm.phoneMsg }}</span>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="editSubmission">确认</el-button>
        <el-button @click="editIsShow = false">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 权限设置弹出框 -->
    <el-dialog title="分配角色" :visible.sync="centerDialogVisible" width="30%" center style="line-height: 20px;">
      <el-form :model="form" ref="formRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="当前用户" prop="username">
          <el-input type="text" autocomplete="off" v-model="form.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="当前角色" prop="role_name">
          <el-input type="text" autocomplete="off" v-model="form.role_name" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_name">
          <el-select v-model="role_name" placeholder="请选择角色">
            <el-option label="主管" value="30"></el-option>
            <el-option label="测试角色" value="31"></el-option>
            <el-option label="测试角色2" value="34"></el-option>
            <el-option label="超级管理员" value="-1"></el-option>
            <el-option label="test" value="40"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="setRoleSubmission">确认</el-button>

          <el-button @click="centerDialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 遮罩层 -->
    <div class="mask " v-show="isShow || editIsShow"></div>
  </div>
</template>

<script>
import page from '../modalBox/page.vue'
import search from '../modalBox/search.vue'
export default {
  components: {
    page,
    search
  },
  data: () => ({
    userList: [],
    placeholder: '请输入用户名',
    pagination: {
      pageSize: 2,
      currentPage: 1
    },
    isAddDialogVisible: false,
    searchKeyword: '',
    isEditDialogVisible: false,
    selectedUserId: '',
    roleSelection: {
      roleId: '',
      roleName: ''
    },
    pagenum: 1,
    pagesize: 2,
    isShow: false,
    searchInput: '',
    editIsShow: false,
    id: '',
    role_id: '',
    role_name: '',
    centerDialogVisible: false,
    total: 0,
    form: {
      id: '',
      username: '',
      password: '',
      email: '',
      phone: '',
      usernameMsg: '',
      passwordMsg: '',
      emailMsg: '',
      phoneMsg: ''
    },
    editForm: {
      username: '',
      email: '',
      phone: '',
      usernameMsg: '',
      emailMsg: '',
      phoneMsg: ''
    }
  }),
  created() {
    this.fetchUserData()
    // .then(data => {
    //   this.userList = data
    //   this.total = data.total
    // })
  },
  mounted() {

  },
  methods: {
    async fetchUserData(pagesize:6, pagenum: this.pagenum) {

  try {
    const res = await this.$Http.get('/users', params);
    console.log(res)
    // return res.data.data;
  } catch (error) {
    // this.$handleError(error, '用户数据加载失败');
    return null;
  }
},
    async addUser() {
  if (this.form.username.length < 3 || this.form.username.length > 6) {
    this.form.usernameMsg = '用户名长度为3-6位'
    return
  } else {
    this.form.usernameMsg = ''
  }
  if (this.form.password.length < 6 || this.form.password.length > 15) {
    this.form.passwordMsg = '密码长度为6-15位'
    return
  } else {
    this.form.passwordMsg = ''
  }
  if (this.form.email.length < 6 || this.form.email.length > 15) {

    this.form.emailMsg = '邮箱长度为6-15位'
    return
  } else {
    this.form.emailMsg = ''
  }
  if (this.form.phone.length !== 11) {
    this.form.phoneMsg = '手机号长度为11位'
    return
  } else {
    this.form.phoneMsg = ''
  }
  try {
    const res = await this.$httpPost('/users', this.form)
    let { data: { data, meta } } = res
    if (meta.status === 201) {
      this.fetchUserData({
        pagesize: this.pagesize,
        pagenum: this.pagenum
      }).then(data => {
        this.userList = data
        this.total = data.total
      })
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      this.isShow = false
    }
  } catch (error) {
    console.error('请求失败:', error)
    this.$message.error('数据加载失败')
    return null
  }

},
editUser(obj) {
  this.editIsShow = true
  console.log(obj);
  this.editForm.username = obj.username
  this.form.id = obj.id
},
    async editSubmission() {
  console.log(this.form.id);
  if (this.editForm.email.length < 6 || this.editForm.email.length > 15) {
    this.editForm.emailMsg = '邮箱长度为6-15位'
    return
  } else {
    this.editForm.emailMsg = ''
  }
  if (this.editForm.phone.length !== 11) {
    this.editForm.phoneMsg = '手机号长度为11位'
    return
  } else {
    this.editForm.phoneMsg = ''
  }
  try {
    const res = await this.$httpPut('/users/' + this.form.id, this.editForm)
    let { data: { data, meta } } = res
    if (meta.status === 200) {
      this.fetchUserData({
        pagesize: this.pagesize,
        pagenum: this.pagenum
      }).then(data => {
        this.userList = data
      })
      this.$message({
        message: '编辑成功',
        type: 'success'
      })
      this.editIsShow = false
    }
  } catch (error) {
    console.error('请求失败:', error)
    this.$message.error('数据加载失败')
    return null
  }
},
    async delUser(obj) {
  try {
    await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    this.id = obj.id
    const res = await this.$httpDelete('/users/' + this.id)
    let { data: { data, meta } } = res
    if (meta.status === 200) {
      this.fetchUserData({
        pagesize: this.pagesize,
        pagenum: this.pagenum
      }).then(data => {
        this.userList = data
        this.total = data.total
      })
      this.$message({
        type: 'success',
        message: meta.msg
      });
    }
  } catch (error) {
    if (error === 'cancel') {
      this.$message({
        type: 'info',
        message: '已取消删除'
      });
    } else {
      console.error('请求失败:', error)
      this.$message.error('数据加载失败')
    }
  }
},
setRole(obj) {
  console.log(obj);
  this.centerDialogVisible = true
  this.form.username = obj.username
  this.form.role_name = obj.role_name
  this.role_id = obj.id
},
    async setRoleSubmission() {
  try {
    const tempArray = {
      id: this.role_id,
      rid: this.role_name
    }
    const res = await this.$httpPut('/users/' + this.role_id + '/role', tempArray)
    let { data: { data, meta } } = res
    if (meta.status === 200) {
      const roleMap = {
        '30': '主管',
        '31': '测试角色',
        '34': '测试角色2',
        '-1': '超级管理员',
        '40': 'test'
      };
      this.fetchUserData({
        pagesize: this.pagesize,
        pagenum: this.pagenum
      }).then(data => {
        this.userList = data
      })
      this.$message({
        message: '修改成功',
        type: 'success'
      })
      this.centerDialogVisible = false
    }
  } catch (error) {
    console.error('请求失败:', error)
    this.$message.error('数据加载失败')
    return null
  }
},
    // 封装搜索逻辑，方便调用
    async performSearch(query) {
  try {
    const params = {
      query: query,
      pagesize: this.pagesize,
      pagenum: this.pagenum
    };
    const res = await this.$httpGet('/users/', params);
    console.log(res);
    this.userList = res.data.data;
    this.$message({
      message: '搜索成功',
      type: 'success'
    });
  } catch (error) {
    this.$handleError(error, '搜索失败');
  }
},
updateCurrentPage(val) {
  this.pagenum = val
  console.log(val);
  this.loadUserList()
},
updatePageSize(val) {
  console.log(val);
  this.pagesize = val
  this.loadUserList()
},
loadUserList() {
  this.fetchUserData({
    pagesize: this.pagesize,
    pagenum: this.pagenum
  }).then(data => {
    this.userList = data
  })
},
    // 搜索用户
    async handleSearch(query) {
  this.searchInput = query
  this.performSearch(this.searchInput);
},
  }
}
</script>
<style scoped lang="scss">
.user-content {
  margin: 20px;
  background-color: #fff;
  height: 800px;
  padding-left: 50px;
}

::v-deep .el-table__header thead tr th {
  height: 30px !important;
  line-height: 30px;
}

.user-form {
  width: 600px;
  height: 500px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}

.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  left: 0;
  top: 0;
  z-index: 3;
}

.edit-form {
  width: 600px;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  // align-items: center;
  background-color: #fff;
  position: fixed;
  text-align: left;
  padding-right: 30px;
  left: 30%;
  top: 20%;
  border-radius: 10px;
  z-index: 4;

  p {
    line-height: 20px;
    margin-left: 30px;
  }

  span {
    display: block;
    height: 20px;
  }
}
</style>